package sk.xorty.jmx;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;

/**
 * Agent that exposes registered MBean - see {@link HelloMBean} and impl {@link Hello}.
 * Can be monitored using JConsole.
 *
 * ======== WARNING: ========
 * RMI Registry must be running on port 9999
 * If agent is modified to run without the RMI connector,
 * JVM argument must be used: -Dcom.sun.management.jmxremote
 *
 * ======== NOTICE ========
 * JConsole ("remote process") can monitor this application using the RMI connector
 * with following URL: service:jmx:rmi:///jndi/rmi://localhost:9999/server
 */
public class SimpleAgent {

    private MBeanServer mbs;

    public SimpleAgent() {
        mbs = ManagementFactory.getPlatformMBeanServer();
        Hello hello = new Hello();
        ObjectName helloName = null;

        try {
            helloName = new ObjectName("SimpleAgent:name=hellothere");
            mbs.registerMBean(hello, helloName);

            // create & start RMI connector
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
            JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SimpleAgent simpleAgent = new SimpleAgent();
        System.out.println("Agent is running ...");
    }
}
